<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="85px">
            <el-form-item label="平台订单号" prop="plateOrderId" >
              <el-input v-model="queryParams.plateOrderId" placeholder="请输入平台订单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="团购劵码" prop="code" >
              <el-input v-model="queryParams.code" placeholder="请输入团购劵码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="使用人" prop="userName">
              <el-input v-model="queryParams.params.userName" placeholder="请输入用户昵称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="用户手机号" prop="userMobile">
              <el-input v-model="queryParams.params.userMobile" placeholder="请输入用户手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态"  prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in ter_group_buy_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="使用时间" prop="useTime">
              <el-date-picker
                v-model="queryParams.params.useTimes"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-240px"
                end-placeholder="结束日期"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="关联ID" prop="relateId">
              <el-input v-model="queryParams.relateId" placeholder="请输入关联ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="关联类型" prop="relateType">
              <el-select v-model="queryParams.relateType" placeholder="请选择关联类型" clearable>
                <el-option v-for="dict in ter_group_buy_relate_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tearoom:groupBuy:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- Tab 选项：真正的内容在 Lab -->
      <el-tabs v-model="activeTab" type="card" @tab-change="onTabChange">
        <el-tab-pane v-for="tab in statusTabs" :key="tab.value" :label="tab.label" :name="tab.value" />
      </el-tabs>

      <el-table v-loading="loading" :data="groupBuyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="false" />
        <el-table-column label="使用人" align="center" prop="userName" />
        <el-table-column label="手机号" align="center" prop="userMobile" width="120px" />
        <el-table-column label="关联类型" align="center" prop="relateType">
          <template #default="scope">
            <dict-tag :options="ter_group_buy_relate_type" :value="scope.row.relateType" />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="平台类型" align="center" prop="plateType">
          <template #default="scope">
            <dict-tag :options="coupon_plate_type" :value="scope.row.plateType" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="ter_group_buy_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="使用时间" align="center" prop="useTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.useTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平台订单号" align="center" prop="plateOrderId" width="180px" />
        <el-table-column label="团购劵码" align="center" prop="code" width="180px" show-overflow-tooltip />
        <el-table-column label="原价" align="center" prop="originalAmount">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.originalAmount) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="实付金额" align="center" prop="payAmount">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.payAmount) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关联ID" align="center" prop="relateId" width="180px" />
        <!-- <el-table-column label="团购类型" align="center" prop="type" /> -->
        <el-table-column label="备注" align="center" prop="remark" />
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tearoom:groupBuy:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tearoom:groupBuy:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="GroupBuy" lang="ts">
import { listGroupBuy, getGroupBuy, delGroupBuy, addGroupBuy, updateGroupBuy } from '@/api/tearoom/groupBuy';
import { GroupBuyVO, GroupBuyQuery, GroupBuyForm } from '@/api/tearoom/groupBuy/types';
import { convertToInteger, formatToFraction, floatToFixed2 } from '@/utils/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ter_group_buy_relate_type, coupon_plate_type, ter_group_buy_status } = toRefs<any>(
  proxy?.useDict('ter_group_buy_relate_type', 'coupon_plate_type', 'ter_group_buy_status')
);

const groupBuyList = ref<GroupBuyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const activeTab = ref('all'); // Tab 筛选
const statusTabs = reactive([
  {
    label: '全部',
    value: 'all'
  },
  {
    label: '美团',
    value: '2'
  },
  {
    label: '抖音',
    value: '3'
  },
  {
    label: '快手',
    value: '4'
  }
]);

const queryFormRef = ref<ElFormInstance>();
const groupBuyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: GroupBuyForm = {
  id: undefined,
  relateId: undefined,
  relateType: undefined,
  name: undefined,
  userId: undefined,
  accountId: undefined,
  status: undefined,
  originalAmount: undefined,
  payAmount: undefined,
  startTime: undefined,
  expireTime: undefined,
  useTime: undefined,
  type: undefined,
  plateType: undefined,
  plateOrderId: undefined,
  remark: undefined
};
const data = reactive<PageData<GroupBuyForm, GroupBuyQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    relateId: undefined,
    relateType: undefined,
    name: undefined,
    userId: undefined,
    accountId: undefined,
    status: undefined,
    originalAmount: undefined,
    payAmount: undefined,
    startTime: undefined,
    expireTime: undefined,
    useTime: undefined,
    type: undefined,
    plateType: undefined,
    plateOrderId: undefined,
    params: {
      userName: undefined,
      userMobile: undefined,
      useTimes: []
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    relateId: [{ required: true, message: '关联ID不能为空', trigger: 'blur' }],
    relateType: [{ required: true, message: '关联类型不能为空', trigger: 'change' }],
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '券的状态不能为空', trigger: 'change' }],
    type: [{ required: true, message: '团购类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询团购核销列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGroupBuy(queryParams.value);
  groupBuyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  groupBuyFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    userName: undefined,
    useTimes: []
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GroupBuyVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加团购核销';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GroupBuyVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getGroupBuy(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改团购核销';
};

/** 提交按钮 */
const submitForm = () => {
  groupBuyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateGroupBuy(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGroupBuy(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: GroupBuyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除团购核销编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delGroupBuy(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'tearoom/groupBuy/export',
    {
      ...queryParams.value
    },
    `groupBuy_${new Date().getTime()}.xlsx`
  );
};

/** tab 切换 */
const onTabChange = (tabName) => {
  queryParams.value.plateType = tabName === 'all' ? undefined : tabName;
  getList();
};

onMounted(() => {
  getList();
});
</script>
